import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { 
  Brain, 
  CheckCircle, 
  XCircle, 
  Calculator, 
  Zap,
  Shield,
  Clock,
  TrendingUp,
  Monitor
} from 'lucide-react';

interface VerificationStep {
  id: string;
  name: string;
  description: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  duration: number;
  technical: string;
}

interface MathOperation {
  id: string;
  name: string;
  formula: string;
  status: 'idle' | 'computing' | 'verified' | 'failed';
  progress: number;
}

export function Stage5Verification() {
  const { blockchainTx, experienceMode, callVerifyAssetZKOnly, zkProofData } = useAppStore();
  const [isVerifying, setIsVerifying] = useState(false);
  const [, setCurrentStep] = useState(-1);
  const [verificationResult, setVerificationResult] = useState<boolean | null>(null);
  const [confidenceScore, setConfidenceScore] = useState(0);
  const [verificationTx, setVerificationTx] = useState<any>(null);
  const [technicalResults, setTechnicalResults] = useState<Record<string, string>>({});
  const [apiResponseDetails, setApiResponseDetails] = useState<any>(null);
  
  const verificationSteps: VerificationStep[] = [
    {
      id: 'receive',
      name: '接收证明数据',
      description: '智能合约接收并解析ABI编码数据',
      status: 'pending',
      duration: 1000,
      technical: '解析calldata中的24个uint256参数'
    },
    {
      id: 'pairing',
      name: '椭圆曲线配对',
      description: '验证G1群元素的数学关系',
      status: 'pending',
      duration: 3000,
      technical: 'e(A,B) = e(α,β) · e(L,γ) · e(C,δ)'
    },
    {
      id: 'polynomial',
      name: '多项式验证',
      description: '检查PLONK多项式约束',
      status: 'pending',
      duration: 4000,
      technical: 'P(z) = Q(z) · Z_H(z) + R(z)'
    },
    {
      id: 'batch',
      name: '批量验证优化',
      description: '使用KZG承诺验证多项式',
      status: 'pending',
      duration: 2000,
      technical: 'KZG.Verify(commitment, point, value, proof)'
    },
    {
      id: 'final',
      name: '最终验证',
      description: '确认零知识证明有效性',
      status: 'pending',
      duration: 1500,
      technical: '返回verification_result = true/false'
    }
  ];
  
  const mathOperations: MathOperation[] = [
    {
      id: 'hash',
      name: 'Poseidon哈希',
      formula: 'H(preImage) = dataHash',
      status: 'idle',
      progress: 0
    },
    {
      id: 'commitment',
      name: 'KZG承诺',
      formula: 'Com(f) = [f(τ)]₁',
      status: 'idle',
      progress: 0
    },
    {
      id: 'pairing_check',
      name: '配对检查',
      formula: 'e(A,B) ≟ e(C,D)',
      status: 'idle',
      progress: 0
    },
    {
      id: 'permutation',
      name: '置换论证',
      formula: '∏ᵢ(aᵢ + βσᵢ + γ) = ∏ᵢ(aᵢ + βi + γ)',
      status: 'idle',
      progress: 0
    }
  ];
  
  const [steps, setSteps] = useState(verificationSteps);
  const [operations, setOperations] = useState(mathOperations);
  
  useEffect(() => {
    if (experienceMode.autoplay) {
      const timer = setTimeout(() => {
        startVerification();
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [experienceMode.autoplay]);

  // 监听区块链交易变化，更新验证交易信息
  useEffect(() => {
    if (blockchainTx && blockchainTx.type === 'verifyAssetZKPacked' && blockchainTx.stage === 'stage5') {
      console.log('📥 检测到Stage5验证交易更新:', blockchainTx);
      setVerificationTx(blockchainTx);
    }
  }, [blockchainTx]);
  
  const startVerification = async () => {
    if (isVerifying) return;
    
    setIsVerifying(true);
    setVerificationResult(null);
    setConfidenceScore(0);
    
    console.log('\n=== 🔍 Stage5: 开始零知识证明验证流程 ===');
    console.log('📊 验证数据:', {
      hasProofData: !!zkProofData,
      hasPreviousTx: !!blockchainTx,
      experienceMode: experienceMode.id
    });
    
    // Start math operations in parallel (UI展示)
    const operationPromises = operations.map(async (op, index) => {
      await new Promise(resolve => setTimeout(resolve, index * 500));
      
      setOperations(prev => prev.map(o => 
        o.id === op.id ? { ...o, status: 'computing' } : o
      ));
      
      // Simulate computation progress
      for (let i = 0; i <= 100; i += 5) {
        setOperations(prev => prev.map(o => 
          o.id === op.id ? { ...o, progress: i } : o
        ));
        await new Promise(resolve => setTimeout(resolve, 30));
      }
      
      setOperations(prev => prev.map(o => 
        o.id === op.id ? { ...o, status: 'verified', progress: 100 } : o
      ));
    });
    
    // Main verification steps with real blockchain call
    for (let i = 0; i < steps.length; i++) {
      setCurrentStep(i);
      
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === i ? 'processing' : index < i ? 'completed' : 'pending'
      })));
      
      console.log(`\n--- 步骤5.${i+1}: ${steps[i].name} ---`);
      console.log(`📝 描述: ${steps[i].description}`);
      console.log(`🔧 技术细节: ${steps[i].technical}`);
      
      // 在每个步骤添加技术参数结果
      if (zkProofData?.proof) {
        const updateTechnicalResults = (stepId: string) => {
          switch (stepId) {
            case 'receive':
              if (zkProofData.proof) {
                const packedProofSize = zkProofData.packedProof?.length || 1602; // 800字节 + 0x前缀
                setTechnicalResults(prev => ({
                  ...prev,
                  [stepId]: `已解析${packedProofSize}字符ABI数据 (800字节proof + 32字节dataHash)`
                }));
              }
              break;
            case 'pairing':
              if (zkProofData.proof?.A && zkProofData.proof?.B) {
                const aX = zkProofData.proof.A[0]?.toString().slice(0, 20) + '...';
                const bX = zkProofData.proof.B[0]?.toString().slice(0, 20) + '...';
                setTechnicalResults(prev => ({
                  ...prev,
                  [stepId]: `e(A[${aX}], B[${bX}]) 配对验证通过`
                }));
              }
              break;
            case 'polynomial':
              if (zkProofData.proof?.eval_a && zkProofData.proof?.eval_b) {
                const evalA = zkProofData.proof.eval_a.toString().slice(0, 15) + '...';
                const evalB = zkProofData.proof.eval_b.toString().slice(0, 15) + '...';
                setTechnicalResults(prev => ({
                  ...prev,
                  [stepId]: `多项式约束验证: eval_a=${evalA}, eval_b=${evalB}`
                }));
              }
              break;
            case 'batch':
              console.log('\n🚀 执行真实的零知识证明验证...');
              
              // 在批量验证步骤调用区块链
              (async () => {
                try {
                  const useSimulation = experienceMode.id === 'presentation' || experienceMode.id === 'quick';
                  console.log('📊 使用模拟模式:', useSimulation);
                  
                  const verificationSuccess = await callVerifyAssetZKOnly(useSimulation);
                  console.log('🔍 验证调用返回结果:', verificationSuccess);
                  
                  // 等待一小段时间让appStore更新
                  await new Promise(resolve => setTimeout(resolve, 100));
                  
                  // 重新获取最新的区块链交易状态
                  const { blockchainTx: latestTx } = useAppStore.getState();
                  console.log('📥 获取最新交易状态:', latestTx);
                  
                  if (verificationSuccess && latestTx && latestTx.stage === 'stage5') {
                    console.log('✅ 区块链验证成功，获取到Stage5交易数据');
                    setVerificationResult(latestTx.verificationResult ?? true);
                    setVerificationTx(latestTx);
                    
                    // 保存详细的API响应数据
                    setApiResponseDetails({
                      success: true,
                      txHash: latestTx.txHash,
                      status: latestTx.status,
                      verificationResult: latestTx.verificationResult,
                      returnValue: latestTx.returnValue,
                      blockNumber: latestTx.blockNumber,
                      gasUsed: latestTx.gasUsed,
                      methodName: latestTx.methodName,
                      contractAddress: latestTx.contractAddress,
                      timestamp: latestTx.timestamp,
                      type: latestTx.type
                    });
                    
                    // 更新技术结果
                    setTechnicalResults(prev => ({
                      ...prev,
                      [stepId]: `KZG验证完成，交易哈希: ${latestTx.txHash?.slice(0, 20)}...，状态: ${latestTx.status}`
                    }));
                  } else {
                    console.log('❌ 区块链验证失败或使用模拟模式');
                    setVerificationResult(false);
                    
                    // 保存失败的API响应数据
                    setApiResponseDetails({
                      success: false,
                      reason: useSimulation ? '使用模拟模式' : '验证调用失败',
                      useSimulation,
                      latestTxInfo: latestTx ? {
                        stage: latestTx.stage,
                        type: latestTx.type,
                        status: latestTx.status
                      } : null
                    });
                    
                    setTechnicalResults(prev => ({
                      ...prev,
                      [stepId]: `KZG验证${useSimulation ? '(模拟模式)' : '失败'}`
                    }));
                  }
                } catch (error) {
                  console.error('❌ 区块链验证调用错误:', error);
                  setVerificationResult(false);
                  
                  // 保存错误的API响应数据
                  setApiResponseDetails({
                    success: false,
                    error: error instanceof Error ? error.message : '未知错误',
                    timestamp: new Date().toISOString()
                  });
                  
                  setTechnicalResults(prev => ({
                    ...prev,
                    [stepId]: `验证调用错误: ${error instanceof Error ? error.message : '未知错误'}`
                  }));
                }
              })();
              break;
            case 'final':
              // 最终验证结果在区块链调用完成后设置
              break;
          }
        };
        
        updateTechnicalResults(steps[i].id);
      }
      
      // Update confidence score
      const baseConfidence = (i + 1) / steps.length * 80;
      for (let conf = confidenceScore; conf <= baseConfidence; conf += 2) {
        setConfidenceScore(conf);
        await new Promise(resolve => setTimeout(resolve, steps[i].duration / 50));
      }
      
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index <= i ? 'completed' : 'pending'
      })));
      
      await new Promise(resolve => setTimeout(resolve, 150));
    }
    
    // Wait for math operations to complete
    await Promise.all(operationPromises);
    
    // Final confidence boost
    for (let conf = confidenceScore; conf <= 100; conf += 1) {
      setConfidenceScore(conf);
      await new Promise(resolve => setTimeout(resolve, 20));
    }
    
    // Final result - 基于真实验证结果或随机生成
    let finalResult = verificationResult;
    if (finalResult === null) {
      finalResult = Math.random() > 0.05; // 95% success rate for simulation
    }
    
    // 更新最终验证技术结果 - 基于API响应详细数据和message字段判断
    if (apiResponseDetails && apiResponseDetails.success) {
      // 真实API调用成功 - 根据message字段判断    
      const isRealVerification = apiResponseDetails.message === 'success';

      console.log('🔍 真实API调用成功:', apiResponseDetails);

      const statusText = isRealVerification ? 'SUCCESS' : 'PENDING';
      
      // 优先使用API响应中的statusOK字段,如果statusOK为true,则验证通过,否则验证失败 
      let verificationText;
      if ('statusOK' in apiResponseDetails) {
        verificationText = apiResponseDetails.statusOK ? 'VALID ✅' : 'INVALID ❌';
      } else {
        verificationText = finalResult ? 'VALID ✅' : 'INVALID ❌';
      }
      
      const resultType = isRealVerification ? '(真实API验证)' : '(API调用成功但状态待定，需共识验证！)';
      
      setTechnicalResults(prev => ({
        ...prev,
        'final': `验证结果: ${verificationText} | 状态: ${statusText} | 区块: #${apiResponseDetails.blockNumber || 'PENDING'} ${resultType}`
      }));
    } else if (apiResponseDetails && !apiResponseDetails.success) {
      // API调用失败但有详细信息
      const reasonText = apiResponseDetails.useSimulation ? '使用模拟模式' : 
                        (apiResponseDetails.reason || apiResponseDetails.error || '未知错误');
      
      setTechnicalResults(prev => ({
        ...prev,
        'final': `验证结果: ${finalResult ? 'VALID ✅' : 'INVALID ❌'} (模拟) | 原因: ${reasonText}`
      }));
    } else {
      // 完全没有API响应数据，使用模拟结果
      setTechnicalResults(prev => ({
        ...prev,
        'final': `验证结果: ${finalResult ? 'VALID ✅' : 'INVALID ❌'} (模拟)`
      }));
    }
    
    setVerificationResult(finalResult);
    
    setIsVerifying(false);
    setCurrentStep(steps.length);
    console.log(`🏁 Stage5验证完成: ${finalResult ? 'VALID' : 'INVALID'}`);
    console.log('📊 技术参数结果:', technicalResults);
  };
  
  const getStepColor = (status: VerificationStep['status']) => {
    switch (status) {
      case 'processing': return 'border-quantum-blue bg-quantum-blue/10';
      case 'completed': return 'border-crypto-green bg-crypto-green/10';
      case 'failed': return 'border-red-400 bg-red-400/10';
      default: return 'border-gray-600 bg-gray-700/50';
    }
  };
  
  const getOperationColor = (status: MathOperation['status']) => {
    switch (status) {
      case 'computing': return 'text-quantum-blue border-quantum-blue';
      case 'verified': return 'text-crypto-green border-crypto-green';
      case 'failed': return 'text-red-400 border-red-400';
      default: return 'text-gray-400 border-gray-600';
    }
  };
  
  return (
    <div className="stage-container">
      <div className="max-w-6xl mx-auto">
        {/* Stage title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <h1 className="text-5xl font-bold gradient-text mb-4">
            🤖 零知识证明验证庭
          </h1>
          <p className="text-xl text-gray-300">
            调用verifyAssetZKPacked执行真实的零知识证明验证
          </p>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left side - AI Judge visualization */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            {/* AI Judge */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Brain className="mr-3 text-quantum-blue" size={28} />
                PlonkVerifier AI法官
              </h3>
              
              <div className="relative h-80 bg-slate-800 rounded-lg p-6 overflow-hidden">
                {/* AI Brain center */}
                <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
                  <motion.div
                    className="w-32 h-32 rounded-full bg-gradient-to-br from-quantum-blue to-proof-purple flex items-center justify-center relative"
                    animate={isVerifying ? {
                      boxShadow: [
                        '0 0 20px rgba(59, 130, 246, 0.3)',
                        '0 0 40px rgba(59, 130, 246, 0.8)',
                        '0 0 20px rgba(59, 130, 246, 0.3)'
                      ]
                    } : {}}
                    transition={{ duration: 2, repeat: isVerifying ? Infinity : 0 }}
                  >
                    <Brain className="w-16 h-16 text-white" />
                    
                    {/* Neural network visualization */}
                    {isVerifying && (
                      <>
                        {Array.from({ length: 8 }, (_, i) => (
                          <motion.div
                            key={i}
                            className="absolute w-2 h-2 bg-white rounded-full"
                            style={{
                              left: '50%',
                              top: '50%',
                              transformOrigin: '0 0',
                            }}
                            animate={{
                              x: Math.cos(i * 45 * Math.PI / 180) * 80,
                              y: Math.sin(i * 45 * Math.PI / 180) * 80,
                              opacity: [0, 1, 0],
                              scale: [0.5, 1, 0.5],
                            }}
                            transition={{
                              duration: 2,
                              delay: i * 0.2,
                              repeat: Infinity,
                            }}
                          />
                        ))}
                      </>
                    )}
                  </motion.div>
                </div>
                
                {/* Mathematical formulas floating around */}
                {operations.map((op, index) => (
                  <motion.div
                    key={op.id}
                    className={`absolute p-2 rounded border ${getOperationColor(op.status)} bg-slate-900/80 backdrop-blur-sm`}
                    style={{
                      left: `${20 + (index % 2) * 60}%`,
                      top: `${20 + Math.floor(index / 2) * 40}%`,
                    }}
                    animate={op.status === 'computing' ? {
                      scale: [1, 1.05, 1],
                      opacity: [0.7, 1, 0.7],
                    } : op.status === 'verified' ? {
                      scale: [1, 1.2, 1],
                    } : {}}
                    transition={{ 
                      duration: 1.5, 
                      repeat: op.status === 'computing' ? Infinity : op.status === 'verified' ? 2 : 0 
                    }}
                  >
                    <div className="text-xs font-mono">{op.name}</div>
                    <div className="text-xs font-mono mt-1">{op.formula}</div>
                    
                    {op.status === 'computing' && (
                      <div className="mt-2 w-full bg-gray-600 rounded-full h-1">
                        <motion.div
                          className="bg-quantum-blue h-1 rounded-full"
                          animate={{ width: `${op.progress}%` }}
                          transition={{ duration: 0.3 }}
                        />
                      </div>
                    )}
                    
                    {op.status === 'verified' && (
                      <div className="mt-1 flex items-center text-crypto-green">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        <span className="text-xs">验证通过</span>
                      </div>
                    )}
                  </motion.div>
                ))}
                
                {/* Confidence meter */}
                <div className="absolute bottom-4 left-4 right-4">
                  <div className="flex justify-between text-xs text-gray-300 mb-2">
                    <span>置信度</span>
                    <span>{confidenceScore.toFixed(0)}%</span>
                  </div>
                  <div className="w-full bg-gray-600 rounded-full h-3">
                    <motion.div
                      className={`h-3 rounded-full transition-colors ${
                        confidenceScore < 50 ? 'bg-red-500' :
                        confidenceScore < 80 ? 'bg-yellow-500' :
                        'bg-crypto-green'
                      }`}
                      animate={{ width: `${confidenceScore}%` }}
                      transition={{ duration: 0.3 }}
                    />
                  </div>
                </div>
              </div>
              
              {/* Control panel */}
              <div className="mt-6">
                <motion.button
                  onClick={startVerification}
                  disabled={isVerifying}
                  whileHover={{ scale: isVerifying ? 1 : 1.02 }}
                  whileTap={{ scale: isVerifying ? 1 : 0.98 }}
                  className={`w-full py-3 px-6 rounded-lg font-semibold transition-all ${
                    isVerifying 
                      ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                      : 'bg-quantum-blue hover:bg-blue-600 text-white'
                  }`}
                >
                  {isVerifying ? (
                    <span className="flex items-center justify-center">
                      <motion.div
                        animate={{ rotate: 360 }}
                        transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                        className="w-5 h-5 border-2 border-white border-t-transparent rounded-full mr-2"
                      />
                      ZK证明验证中... {confidenceScore.toFixed(0)}%
                    </span>
                  ) : (
                    <span className="flex items-center justify-center">
                      <Shield className="w-5 h-5 mr-2" />
                      🤖 开始ZK验证
                    </span>
                  )}
                </motion.button>
              </div>
            </div>
            
            {/* Verification Transaction Details */}
            {verificationTx && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="floating-card"
              >
                <h3 className="text-lg font-semibold text-white mb-4">🔍 验证交易详情</h3>
                <div className="space-y-3 text-sm">
                  <div className="bg-slate-800 rounded p-3">
                    <div className="text-gray-300 mb-1">交易哈希</div>
                    <div className="font-mono text-xs text-quantum-blue break-all">
                      {verificationTx.txHash || '0x' + '0'.repeat(64)}
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-3">
                    <div className="bg-slate-800 rounded p-3 text-center">
                      <div className="text-gray-300 text-xs">区块高度</div>
                      <div className="text-lg font-semibold text-purple-400">
                        #{verificationTx.blockNumber || 'pending'}
                      </div>
                    </div>
                    
                    <div className="bg-slate-800 rounded p-3 text-center">
                      <div className="text-gray-300 text-xs">Gas消耗</div>
                      <div className="text-lg font-semibold text-orange-400">
                        {verificationTx.gasUsed?.toLocaleString() || '0'}
                      </div>
                    </div>
                  </div>
                  
                  <div className="bg-slate-800 rounded p-3">
                    <div className="text-gray-300 mb-1">调用方法</div>
                    <div className="text-crypto-green font-mono text-sm">
                      verifyAssetZKPacked(packedProof)
                    </div>
                  </div>
                  
                  {/* 验证结果 */}
                  {verificationResult !== null && (
                    <div className={`rounded p-3 border-l-4 ${
                      verificationResult 
                        ? 'bg-green-900/20 border-crypto-green' 
                        : 'bg-red-900/20 border-red-400'
                    }`}>
                      <div className="text-gray-300 mb-1">验证结果</div>
                      <div className={`font-semibold text-lg ${
                        verificationResult ? 'text-crypto-green' : 'text-red-400'
                      }`}>
                        {verificationResult ? '✅ PROOF VALID' : '❌ PROOF INVALID'}
                      </div>
                    </div>
                  )}
                  
                  {/* 返回数据 */}
                  {verificationTx.returnValue && (
                    <div className="bg-slate-800 rounded p-3">
                      <div className="text-gray-300 mb-1">返回数据</div>
                      <div className="font-mono text-xs text-gray-400 break-all">
                        {verificationTx.returnValue}
                      </div>
                    </div>
                  )}
                  
                  {/* 交易时间戳 */}
                  {verificationTx.timestamp && (
                    <div className="flex justify-between text-xs">
                      <span className="text-gray-400">交易时间:</span>
                      <span className="text-gray-300">
                        {new Date(verificationTx.timestamp).toLocaleString()}
                      </span>
                    </div>
                  )}
                </div>
              </motion.div>
            )}
            
            {/* API Response Details */}
            {apiResponseDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.3 }}
                className="floating-card border border-blue-500/30"
              >
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
                  <Monitor className="mr-2 text-blue-400" size={20} />
                  📊 详细API响应数据
                </h3>
                
                <div className="space-y-3">
                  {/* API调用状态 */}
                  <div className="bg-slate-800 rounded p-3">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-gray-300 font-medium">API调用状态</span>
                      <span className={`px-2 py-1 rounded text-xs font-semibold ${
                        apiResponseDetails.success 
                          ? 'bg-green-500/20 text-green-400 border border-green-500/30' 
                          : 'bg-red-500/20 text-red-400 border border-red-500/30'
                      }`}>
                        {apiResponseDetails.success ? 'SUCCESS' : 'FAILED'}
                      </span>
                    </div>
                    
                    {apiResponseDetails.success ? (
                      <div className="text-green-400 text-sm">
                        ✅ verifyAssetZKPacked API调用成功
                      </div>
                    ) : (
                      <div className="text-red-400 text-sm">
                        ❌ {apiResponseDetails.reason || apiResponseDetails.error || 'API调用失败'}
                      </div>
                    )}
                  </div>

                  {/* 响应状态字段 */}
                  {apiResponseDetails.success && apiResponseDetails.status && (
                    <div className="bg-slate-800 rounded p-3">
                      <div className="text-gray-300 font-medium mb-2">响应状态字段</div>
                      <div className="flex items-center space-x-2">
                        <span className="text-sm text-gray-400">status:</span>
                        <span className={`px-2 py-1 rounded text-xs font-semibold ${
                          apiResponseDetails.status === 'success' 
                            ? 'bg-green-500/20 text-green-400' 
                            : 'bg-yellow-500/20 text-yellow-400'
                        }`}>
                          {apiResponseDetails.status}
                        </span>
                      </div>
                    </div>
                  )}

                  {/* 验证结果字段 */}
                  {apiResponseDetails.success && apiResponseDetails.verificationResult !== undefined && (
                    <div className="bg-slate-800 rounded p-3">
                      <div className="text-gray-300 font-medium mb-2">验证结果字段</div>
                      <div className="flex items-center space-x-2">
                        <span className="text-sm text-gray-400">verificationResult:</span>
                        <span className={`px-2 py-1 rounded text-xs font-semibold ${
                          apiResponseDetails.verificationResult 
                            ? 'bg-green-500/20 text-green-400' 
                            : 'bg-red-500/20 text-red-400'
                        }`}>
                          {apiResponseDetails.verificationResult ? 'true' : 'false'}
                        </span>
                      </div>
                    </div>
                  )}

                  {/* 交易详情 */}
                  {apiResponseDetails.success && (
                    <div className="bg-slate-800 rounded p-3">
                      <div className="text-gray-300 font-medium mb-2">交易详情</div>
                      <div className="space-y-2 text-sm">
                        {apiResponseDetails.txHash && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">交易哈希:</span>
                            <span className="text-blue-400 font-mono text-xs">
                              {apiResponseDetails.txHash.slice(0, 10)}...{apiResponseDetails.txHash.slice(-6)}
                            </span>
                          </div>
                        )}
                        
                        {apiResponseDetails.blockNumber && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">区块号:</span>
                            <span className="text-purple-400">#{apiResponseDetails.blockNumber}</span>
                          </div>
                        )}
                        
                        {apiResponseDetails.gasUsed && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">Gas消耗:</span>
                            <span className="text-orange-400">{apiResponseDetails.gasUsed.toLocaleString()}</span>
                          </div>
                        )}
                        
                        {apiResponseDetails.methodName && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">调用方法:</span>
                            <span className="text-crypto-green font-mono">{apiResponseDetails.methodName}</span>
                          </div>
                        )}
                        
                        {apiResponseDetails.timestamp && (
                          <div className="flex justify-between">
                            <span className="text-gray-400">时间戳:</span>
                            <span className="text-gray-300 text-xs">
                              {new Date(apiResponseDetails.timestamp).toLocaleString()}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  )}

                  {/* 返回值 */}
                  {apiResponseDetails.success && apiResponseDetails.returnValue && (
                    <div className="bg-slate-800 rounded p-3">
                      <div className="text-gray-300 font-medium mb-2">返回值</div>
                      <div className="font-mono text-xs text-gray-400 break-all bg-slate-900 p-2 rounded">
                        {apiResponseDetails.returnValue}
                      </div>
                    </div>
                  )}

                  {/* 模拟模式信息 */}
                  {!apiResponseDetails.success && apiResponseDetails.useSimulation && (
                    <div className="bg-yellow-500/10 border border-yellow-500/30 rounded p-3">
                      <div className="text-yellow-400 font-medium mb-2">⚠️ 模拟模式</div>
                      <div className="text-yellow-300 text-sm">
                        当前使用模拟模式，未实际调用区块链API。真实模式需要连接到WeBASE网关。
                      </div>
                    </div>
                  )}

                  {/* 错误信息 */}
                  {!apiResponseDetails.success && apiResponseDetails.error && (
                    <div className="bg-red-500/10 border border-red-500/30 rounded p-3">
                      <div className="text-red-400 font-medium mb-2">❌ 错误信息</div>
                      <div className="text-red-300 text-sm font-mono">
                        {apiResponseDetails.error}
                      </div>
                    </div>
                  )}
                </div>
              </motion.div>
            )}
            
            {/* Previous Transaction (Data Registration) */}
            {verificationTx?.previousTransaction && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
                className="floating-card border border-gray-600"
              >
                <h3 className="text-sm font-semibold text-gray-300 mb-3">📝 关联的数据上链交易</h3>
                <div className="text-xs text-gray-400 space-y-1">
                  <div>哈希: {verificationTx.previousTransaction.txHash?.slice(0, 20)}...</div>
                  <div>方法: recordAsset</div>
                  <div>区块: #{verificationTx.previousTransaction.blockNumber || 'N/A'}</div>
                </div>
              </motion.div>
            )}
          </motion.div>
          
          {/* Right side - Verification steps */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Steps list */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6">📋 验证流程</h3>
              
              <div className="space-y-4">
                {steps.map((step) => (
                  <motion.div
                    key={step.id}
                    className={`p-4 rounded-lg border transition-all ${getStepColor(step.status)}`}
                  >
                    <div className="flex items-start space-x-3">
                      <div className="mt-1">
                        {step.status === 'processing' ? (
                          <motion.div
                            animate={{ rotate: 360 }}
                            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                            className="w-5 h-5 border-2 border-quantum-blue border-t-transparent rounded-full"
                          />
                        ) : step.status === 'completed' ? (
                          <CheckCircle className="w-5 h-5 text-crypto-green" />
                        ) : step.status === 'failed' ? (
                          <XCircle className="w-5 h-5 text-red-400" />
                        ) : (
                          <Clock className="w-5 h-5 text-gray-400" />
                        )}
                      </div>
                      
                      <div className="flex-1">
                        <h4 className="font-semibold text-white">{step.name}</h4>
                        <p className="text-gray-300 text-sm mt-1">{step.description}</p>
                        
                        {/* Technical details - 显示真实结果或默认公式 */}
                        {experienceMode.showTechDetails && (
                          <div className="mt-2 bg-slate-900 rounded p-2 text-xs font-mono">
                            {technicalResults[step.id] ? (
                              <span className="text-crypto-green">
                                📊 {technicalResults[step.id]}
                              </span>
                            ) : (
                              <span className="text-gray-400">
                                📝 {step.technical}
                              </span>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
            
            {/* Verification result */}
            {verificationResult !== null && (
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ type: "spring", stiffness: 200 }}
                className={`floating-card ${
                  verificationResult 
                    ? 'border-crypto-green bg-crypto-green/5' 
                    : 'border-red-400 bg-red-400/5'
                }`}
              >
                <div className="text-center">
                  <motion.div
                    animate={verificationResult ? { 
                      scale: [1, 1.2, 1],
                      rotate: [0, 10, -10, 0]
                    } : {
                      scale: [1, 1.1, 1]
                    }}
                    transition={{ duration: 1, repeat: 3 }}
                    className="text-8xl mb-4"
                  >
                    {verificationResult ? '✅' : '❌'}
                  </motion.div>
                  
                  <h3 className={`text-3xl font-bold mb-4 ${
                    verificationResult ? 'text-crypto-green' : 'text-red-400'
                  }`}>
                    {verificationResult ? '验证成功！' : '验证失败！'}
                  </h3>
                  
                  <p className="text-gray-300 mb-6">
                    {verificationResult 
                      ? '恭喜！您的零知识证明已通过AI法官的严格审核。您成功证明了对秘密数据的知识，同时完美保护了隐私。'
                      : '很抱歉，证明验证失败。请检查输入数据或重新生成证明。'
                    }
                  </p>
                  
                  {verificationResult && (
                    <div className="grid grid-cols-3 gap-4 mb-6">
                      <div className="bg-slate-700 rounded p-3 text-center">
                        <TrendingUp className="w-6 h-6 mx-auto mb-2 text-crypto-green" />
                        <div className="text-sm text-gray-300">置信度</div>
                        <div className="text-lg font-semibold text-crypto-green">{confidenceScore}%</div>
                      </div>
                      
                      <div className="bg-slate-700 rounded p-3 text-center">
                        <Calculator className="w-6 h-6 mx-auto mb-2 text-blue-400" />
                        <div className="text-sm text-gray-300">数学验证</div>
                        <div className="text-lg font-semibold text-blue-400">通过</div>
                      </div>
                      
                      <div className="bg-slate-700 rounded p-3 text-center">
                        <Zap className="w-6 h-6 mx-auto mb-2 text-purple-400" />
                        <div className="text-sm text-gray-300">验证时间</div>
                        <div className="text-lg font-semibold text-purple-400">2.3s</div>
                      </div>
                    </div>
                  )}
                  
                  <motion.div
                    className="text-quantum-blue"
                    animate={{ y: [0, -10, 0] }}
                    transition={{ duration: 2, repeat: Infinity }}
                  >
                    <span className="text-2xl">{verificationResult ? '🎉' : '🔄'}</span>
                    <p className="font-semibold">
                      {verificationResult ? '准备展示最终结果...' : '可以重新尝试验证...'}
                    </p>
                  </motion.div>
                </div>
              </motion.div>
            )}
            
            {/* Technical explanation */}
            {experienceMode.showTechDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1 }}
                className="bg-slate-800/50 rounded-lg p-4 border border-slate-700"
              >
                <h4 className="text-lg font-semibold text-white mb-3">🔬 验证原理</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <p>• <strong>椭圆曲线配对：</strong>验证双线性映射关系</p>
                  <p>• <strong>多项式承诺：</strong>使用KZG承诺验证计算正确性</p>
                  <p>• <strong>PLONK协议：</strong>通用的zk-SNARK验证算法</p>
                  <p>• <strong>零知识性：</strong>验证过程不泄露任何秘密信息</p>
                </div>
              </motion.div>
            )}
          </motion.div>
        </div>
      </div>
    </div>
  );
}